//
//  Render.m
//  gpuImage
//
//  Created by 王洪飞 on 2024/6/4.
//

#import "Render.h"
#import <GLKit/GLKit.h>
#import <OpenGLES/ES3/gl.h>
#import <OpenGLES/ES3/glext.h>
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"

@interface Render ()
{
    EAGLContext *mContext;
    CAEAGLLayer *mEagllayer;
    GLuint frameBuffer;
    GLuint renderBuffer;
    
}
-(void)setupContext;
-(void)setupEagllayer;
-(void)setupFramebuffer;
-(void)setupRenderbuffer;
-(void)draw;
-(void)destory;
@end

@implementation Render

//- (instancetype)initWithFrame:(CGRect)frame
//{
//    self = [super initWithFrame:frame];
//    if (self) {
//        self.backgroundColor = [UIColor whiteColor];
//        
//    }
//    return self;
//}

+ (Class)layerClass{
    return  [CAEAGLLayer class];
}

- (void)setupContext{
    mContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3];
    [EAGLContext setCurrentContext:mContext];
}
-(void)setupEagllayer{
    mEagllayer = (CAEAGLLayer *)self.layer;
    mEagllayer.drawableProperties = @{
        kEAGLDrawablePropertyColorFormat: kEAGLColorFormatRGBA8,
        kEAGLDrawablePropertyRetainedBacking: @(NO)
    };
    mEagllayer.opaque = NO;
}

- (void)setupRenderbuffer{
    glGenRenderbuffers(1, &renderBuffer);
    glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer);
    [mContext renderbufferStorage:GL_RENDERBUFFER fromDrawable:mEagllayer];
}

-(void)setupFramebuffer{
    glGenFramebuffers(1, &frameBuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderBuffer);
}

-(void)destory{
    glDeleteRenderbuffers(1, &renderBuffer);
    renderBuffer = 0;
    glDeleteFramebuffers(1, &frameBuffer);
    frameBuffer = 0;
}
-(void)draw{
    glClearColor(1, 0, 1, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    [mContext presentRenderbuffer:GL_RENDERBUFFER];
    
}


- (void)layoutSubviews{
    [self setupContext];
    [self setupEagllayer];
    [self destory];
    [self setupRenderbuffer];
    [self setupFramebuffer];
    [self draw];
}



@end


#pragma clang diagnostic pop
